import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:table_calendar/table_calendar.dart';

import '../../base/imageres.dart';
import '../../base/constant.dart';
import '../../base/lang.dart';
import '../../base/log.dart';
import '../../base/stringres.dart';
import '../../base/theme.dart';
import '../../util/toast_util.dart';
import '../../views/jsw_base_view.dart';

///女性健康下面的月经最近的一次时间
class MenstrualTimePage extends StatefulWidget {
  final int cycleValue;
  final int periodValue;

  const MenstrualTimePage(
      {super.key, required this.cycleValue, required this.periodValue});

  @override
  State<StatefulWidget> createState() {
    return _MenstrualTimePageState();
  }
}

class _MenstrualTimePageState extends State<MenstrualTimePage> {
  static const _tag = '[page_menstrual_time.dart][_MenstrualTimePageState]';

  ///UI显示的日期范围
  final Set<DateTime> _selectedDates = {};

  ///存储的时间戳
  int _menstrualTime = 0;

  ///生理周期的值
  var _cycleValue = 0;

  ///经期长度的值
  var _periodValue = 0;

  DateTime _focusedDateTime = DateTime.now();

  @override
  void initState() {
    super.initState();
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual,
        overlays: SystemUiOverlay.values);
    _cycleValue = widget.cycleValue;
    _periodValue = widget.periodValue;
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Container(
          decoration: const BoxDecoration(
            image: DecorationImage(
              image: AssetImage(ImageRes.bg_health_set),
              fit: BoxFit.cover, // 图片填充方式
            ),
          ),
        ),
        JSWBaseView(
          bodyColor: Colors.transparent,
          head: AppBar(
            elevation: 0.0,
            backgroundColor: Colors.transparent,
            title: EasyTouch(
              width: double.infinity,
              padding: const EdgeInsets.only(right: 55),
              child: Text(
                StringRes.women_cycle_title,
                textAlign: TextAlign.center,
                style: ThemeUtil.toolbar,
              ),
            ),
            leading: IconButton(
              splashColor: Colors.transparent,
              highlightColor: Colors.transparent,
              hoverColor: Colors.transparent,
              icon: const Icon(
                Icons.arrow_back,
                color: Colors.white,
              ),
              onPressed: () {
                Get.back();
              },
            ),
          ),
          body: SingleChildScrollView(
            child: Column(
              children: [
                //内容
                Container(
                    margin: const EdgeInsets.only(top: 20, left: 20, right: 20),
                    child: Text(
                      textAlign: TextAlign.center,
                      StringRes.women_time_content,
                      style: ThemeUtil.h1.copyWith(fontSize: 20),
                    )),

                //提示
                Container(
                    margin: const EdgeInsets.only(top: 10, left: 20, right: 20),
                    child: Text(
                      StringRes.women_time_tips,
                      textAlign: TextAlign.center,
                      style: ThemeUtil.p2.copyWith(
                          color: const Color(ThemeUtil.primaryWhiteValue50)),
                    )),

                //时间选择器
                Container(
                    margin: const EdgeInsets.only(top: 30, left: 15, right: 15),
                    padding:
                    const EdgeInsets.only(bottom: 20, left: 15, right: 15),
                    decoration: BoxDecoration(
                      color: Colors.white12,
                      borderRadius: BorderRadius.circular(25.0), // 设置圆角半径
                    ),
                    child: TableCalendar<String>(
                      daysOfWeekHeight: 32.0,
                      locale: S.getCalendarLocale(),
                      firstDay: DateTime.utc(1970, 1, 1),
                      lastDay: DateTime.utc(DateTime.now().year,
                          DateTime.now().month, getDaysInMonth(DateTime.now())),
                      focusedDay: _focusedDateTime,
                      selectedDayPredicate: (day) {
                        return _selectedDates
                            .any((selectedDate) => isSameDay(selectedDate, day));
                      },
                      headerStyle: const HeaderStyle(
                        titleTextStyle: TextStyle(
                            color: Colors.white,
                            fontSize: 18,
                            fontWeight: FontWeight.normal),
                        leftChevronIcon: Icon(
                          Icons.chevron_left,
                          color: Colors.white,
                          size: 30,
                        ),
                        rightChevronIcon: Icon(
                          Icons.chevron_right,
                          color: Colors.white,
                          size: 30,
                        ),
                        titleCentered: true,
                        leftChevronVisible: true,
                        rightChevronVisible: true,
                        formatButtonVisible: false,
                      ),
                      daysOfWeekStyle: const DaysOfWeekStyle(
                        weekdayStyle: TextStyle(color: Colors.white),
                        weekendStyle: TextStyle(color: Colors.white),
                      ),
                      calendarStyle: const CalendarStyle(
                        weekendTextStyle: TextStyle(color: Colors.white),
                        defaultTextStyle: TextStyle(color: Colors.white),
                        todayTextStyle: TextStyle(color: Colors.white),
                        todayDecoration: BoxDecoration(color: Colors.transparent),
                        holidayTextStyle: TextStyle(color: Colors.white),
                        selectedTextStyle: TextStyle(color: Colors.white),
                        selectedDecoration: BoxDecoration(
                            color: Color(ThemeUtil.primaryCalendarSelectValue),
                            shape: BoxShape.circle),
                        outsideTextStyle: TextStyle(color: Colors.transparent),
                        disabledTextStyle: TextStyle(color: Colors.transparent),
                      ),
                      onDaySelected: (selectedDay, focusedDay) {
                        _selectedDates.clear();
                        // 添加月经期长度
                        for (int i = 0; i < _periodValue; i++) {
                          DateTime date = DateTime(selectedDay.year,
                              selectedDay.month, selectedDay.day + i);
                          _selectedDates.add(date);
                        }
                        var dateString = DateFormat("yyyy-MM-dd")
                            .format(selectedDay)
                            .toString();
                        DartLog.i(
                            _tag, "onDaySelected====$_periodValue $dateString");
                        _selectedDates.add(selectedDay);
                        _menstrualTime = selectedDay.millisecondsSinceEpoch;
                        _focusedDateTime = selectedDay;
                        setState(() {});
                      },
                    )),

              ],
            ),
          ),
          bottom: Container(
            margin: EdgeInsets.only(bottom: 30 + MediaQuery.of(context).viewPadding.bottom, left: 30, right: 30),
            child: //下一步按钮
                Container(
              height: 50,
              alignment: Alignment.center,
              decoration: ThemeUtil.themeConStyle,
              child: TextButton(
                style: ThemeUtil.themebtnStyle,
                onPressed: () async {
                  if (_menstrualTime <= 0) {
                    ToastUtil.show(StringRes.menstrual_time_is_null_tips);
                    return;
                  }
                  Get.toNamed(PageIndex.periodicLawPage, arguments: {
                    "isReset": false,
                    "regularly": -1,
                    "menstrualTime": _menstrualTime,
                    "cycleValue": _cycleValue,
                    "periodValue": _periodValue
                  });
                },
                child: Text(StringRes.next_step,
                    textAlign: TextAlign.center, style: ThemeUtil.p2),
              ),
            ),
          ),
        ),
      ],
    );
  }

  /// 获取指定日期所在月份的天数
  int getDaysInMonth(DateTime date) {
    DateTime nextMonth = DateTime(date.year, date.month + 1, 1);
    DateTime lastDayOfMonth = nextMonth.subtract(const Duration(days: 1));
    return lastDayOfMonth.day;
  }
}
